package br.ds.twitter4a;

import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import br.ds.twitter4a.async.oauth.TwitterAccessTokenTask;
import br.ds.twitter4a.async.oauth.TwitterRequestTokenTask;
import br.ds.twitter4a.callback.TwitterAccessTokenCallback;
import br.ds.twitter4a.callback.TwitterRequestTokenCallback;
import br.ds.twitter4a.rest.util.ConsumerKeys;
import br.ds.twitter4a.rest.util.TwitterPreferences;

public class TwitterActivity extends Activity implements
	TwitterAccessTokenCallback, TwitterRequestTokenCallback {

    /** {@inheritDoc} */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);

	if (getIntent().getData() == null) {
	    // Called for get the request token.
	    new TwitterRequestTokenTask(getApplicationContext(), this)
		    .execute();
	} else {
	    // On the return of the get request token.
	    final String oauthVerifier = getIntent().getData()
		    .getQueryParameter("oauth_verifier");
	    new TwitterAccessTokenTask(getApplicationContext(), this)
		    .execute(oauthVerifier);
	}
    }

    /** {@inheritDoc} */
    @Override
    public void onRequestTokenStarted() {
	// Get back to the previous screen.
	this.finish();
    }

    /** {@inheritDoc} */
    @Override
    public void onRequestTokenInterrupted() {
	Log.e("TwitterActivity", "onRequestTokenInterrupted");
    }

    /** {@inheritDoc} */
    @Override
    public void onAccessTokenSaved() {
	Log.e("TwitterActivity", "onAccessTokenSaved");
	new AsyncTask<Void, Void, Void>() {

	    @Override
	    protected Void doInBackground(Void... params) {
		final TwitterPreferences preferences = TwitterPreferences
			.getInstance(getApplicationContext());

		final AccessToken accessToken = new AccessToken(
			preferences.retrieveAcssesToken(),
			preferences.retrieveTokenSecret());
		final Twitter twitter = new TwitterFactory().getInstance();
		twitter.setOAuthConsumer(ConsumerKeys.CONSUMER_KEY,
			ConsumerKeys.CONSUMER_SECRET);
		twitter.setOAuthAccessToken(accessToken);
		try {
		    twitter.updateStatus("Testing New Twitter Lib \\o/ "
			    + System.currentTimeMillis());
		} catch (final TwitterException exception) {
		    Log.e("TwitterActivity", "Bugou Geral");
		}
		return null;
	    }
	}.execute();

    }

    /** {@inheritDoc} */
    @Override
    public void onAccessTokenError() {
	Log.e("TwitterActivity", "onAccessTokenError");
    }

}
